package controllers.admin;

import java.util.ArrayList;
import java.util.List;

import org.bson.types.ObjectId;

import models.bbs.Article;
import models.bbs.Pager;
import models.user.Role;
import models.user.User;
import play.data.validation.Required;
import play.mvc.Controller;

public class Users extends Controller {
	
	public static void list(int page){
		if(page == 0) page = 1;
		
		int offset = (page - 1) * Pager.rowsPerPages;
		List<User> users = User.find().order("userId").offset(offset).limit(Pager.rowsPerPages).asList();
		Pager pager = new Pager("", User.find().count(), page);
		render(users, pager);
		render();
	}
	
	public static void view(ObjectId id){
		System.out.println("id: "+ id);
		User user = User.findById(id);
		render(user);
	}
	
	public static void delete(ObjectId id){
		User user = User.findById(id);
		user.delete();
		list(0);
	}
	
	public static void write(){
		render();
	}
	
	public static void writeb(@Required String userId, @Required String name, @Required String password, @Required String password_confirm){
		if(validation.hasErrors()) {
		       params.flash(); 
		       validation.keep(); 
		       write();
		 }else if(!password.equals(password_confirm)){
			 write();
		 }
		User user = new User(name, userId, password);
		user.save();
//		
		list(0);
	}
	
	public static void edit(ObjectId id){
		User user = User.findById(id);
		Role[] roles = Role.values();
		render(user, roles);
	}
	
	public static void editb(ObjectId id, @Required String name, @Required String password, @Required String password_confirm){
		if(validation.hasErrors()) {
		       params.flash(); 
		       validation.keep(); 
		       write();
		 }else if(!password.equals(password_confirm)){
			 write();
		 }
		
		System.out.println(id);
		List<Role> roles = new ArrayList<Role>();
		for(Role role : Role.values()){
			if("on".equals(params.get(role.name()))){
				roles.add(role);
			}
		}
		User user = User.findById(id);
		user.setName(name);
		user.setPassword(password);
		user.setRoleSet(roles);
		user.save();
//		
		list(0);
	}
}
